<?php
include_once 'application/controllers/AbstractController.php';
require_once 'application/models/Serie.php';

class SerieController extends AbstractController 
{
	function indexAction()
    {
		parent::indexAction();
    	HttpUtil::do405();
    }
    
    
    function getAction()
    {
		parent::getAction();
    	HttpUtil::do405();
    }
    
    function postAction()
    {
		parent::postAction();
		$batterieId = $this->getRequest()->getParam('batterie');
		$serieNumber = $this->getRequest()->getParam('serie');
		$name = $this->getRequest()->getParam('nom');
		$description = $this->getRequest()->getParam('description');
		
		$isValid = TypeChecker::validate(array(
			array('data' => $batterieId, 'type' => TypeChecker::$_NUM_TYPE, 'name' => 'batterie'),
			array('data' => $serieNumber, 'type' => TypeChecker::$_NUM_TYPE, 'name' => 'serie')
			));
		if ($isValid !== true) {
			HttpUtil::do400('validation', $isValid);
		}

		$table = new Serie();
		
		// delete if existing
		$where = array();
		$where[] = $table->getAdapter()->quoteInto('batterie_id = ?', $batterieId);
		$where[] = $table->getAdapter()->quoteInto('serie_number = ?', $serieNumber);
		$table = $table->delete($where);
		
		$table = new Serie();
		
		// if "name" is empty : do nothing
		if ($name != '') {
			
			// insert data
			try {
				$data = array(
					'batterie_id' => $batterieId,
					'serie_number' => $serieNumber,
					'nom' => $name,
					'description' => $description
				);
				 
				$lastInsertId = $table->insert($data);	    
			}catch(Exception $exception) {
				HttpUtil::do400('creation_failed');
			}
			
		}
			
   		$this->view->data = json_encode(array(
   			'id' => $lastInsertId,
			'batterie_id' => $batterieId,
			'serie_number' => $serieNumber,
			'nom' => $name,
			'description' => $description
   		));
    }
    
    function putAction()
    {
		parent::putAction();
    	HttpUtil::do405();
	}
	
    function deleteAction()
    {
		parent::deleteAction();
    	HttpUtil::do405();
    }
}
